﻿using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using SUNRPA.CONTROLS.IMPL.domain;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// 文件操作工具类
/// </summary>
namespace SUNRPA.CONTROLS.IMPL.util {
    public class FileUtil {
        public static byte[] GetFileBtyeData() { 
            return null;
        }

        public static Object GetFileObj() { 
            return null;
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        public static DirectoryInfo CreateDirectory(string dirPath) { 
            return Directory.CreateDirectory(dirPath);
        }

        /// <summary>
        /// 向文件中写文字
        /// </summary>
        public static void WriteToFile(string filePath, string content) {
            using(StreamWriter stream = new StreamWriter(new FileStream(filePath, FileMode.Create))) { 
                stream.WriteLine(content);
            }
        }
        /// <summary>
        /// 打开文件选择器
        /// </summary>
        /// <param name="defaultExt">默认文件扩展名</param>
        /// <param name="filter">扩展名过滤器</param>
        /// <param name="initialDirectory">初始目录</param>
        public static Microsoft.Win32.OpenFileDialog OpenFileSelectDialog(string defaultExt, string filter, string initialDirectory) {
            Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
            openFileDlg.DefaultExt = defaultExt;
            openFileDlg.Filter = filter;
            // 设置初始目录
            openFileDlg.InitialDirectory = initialDirectory;
            //允许多选
            //openFileDlg.Multiselect = true;
            //openFileDlg.Filter = "All files (*.*)|*.*";
            return openFileDlg;
        }
        /// <summary>
        /// 保存文件对话框
        /// </summary>
        /// <param name="defaultExt"></param>
        /// <param name="filter"></param>
        /// <param name="initialDirectory"></param>
        /// <returns></returns>
        public static SaveFileDialog OpenSaveFileDialog(string filter) {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = filter;
            return saveFileDialog;
        }

        public static FolderBrowserDialog OpenFloderSelectDialog() { 
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择文件夹";
            return fd;
        }

        /// <summary>
        /// 直接打开文件或者文件夹
        /// </summary>
        /// <param name="path">路径</param>
        public static Process OpenFolderOrFileDirectly(string path) { 
            return Process.Start(path);
        }

        public static void CreateFile(string filePath, [Optional]byte[] content) {
            if(content != null) { 
                File.WriteAllBytes(filePath, content);
            } else { 
                File.Create(filePath).Close();
            }
        }

        /// <summary>
        /// 创建压缩文件
        /// </summary>
        public static byte[] CreateZipFromMemory(Dictionary<string, byte[]> entrys) { 
            using(MemoryStream ms = new MemoryStream()) { 
                using(ZipOutputStream zo = new ZipOutputStream(ms)) {
                    foreach(string key in entrys.Keys) { 
                        byte[] data = entrys[key];
                        ZipEntry entry = new ZipEntry(key);
                        entry.DateTime = DateTime.Now;
                        entry.Size = data.Length;
                        zo.PutNextEntry(entry);
                        zo.Write(data, 0, (int)entry.Size);
                        zo.CloseEntry();
                    }
                    zo.Finish();
                }
                byte[] result = ms.ToArray();
                return result;
            }
        }

        public static byte[] CreateZipFromMemory(Dictionary<string, string> entrys) { 
            Dictionary<string, byte[]> bytesEntry = new Dictionary<string, byte[]>();
            foreach(string key in entrys.Keys) { 
                byte[] data = Encoding.UTF8.GetBytes(entrys[key]);
                bytesEntry.Add(key, data);
            }
            return CreateZipFromMemory(bytesEntry);
        }

        public static void CreateZipFileByBytes(byte[] outBytes, string fileFullPath) { 
            File.WriteAllBytes(fileFullPath, outBytes);
        }

        public static T DeserializeZipContentFromBytes<T>(String name, byte[] zipBytes) { 
            using(MemoryStream ms = new MemoryStream()) {
                ms.Write(zipBytes,0,zipBytes.Length);
                using(ZipFile zip = new ZipFile(ms)) { 
                    ZipEntry entry = zip.GetEntry(name);
                    if(entry == null) { 
                        throw new RpaBuildingException("流程数据缺失，流程已损坏");
                    }
                    using(Stream stream = zip.GetInputStream(entry)) { 
                        byte[] buffer = new byte[10240];
                        int length = 0;
                        using(MemoryStream temp = new MemoryStream()) { 
                            while((length = stream.Read(buffer, 0, buffer.Length)) > 0) {
                                temp.Write(buffer, 0, length);
                            }
                            byte[] data = temp.ToArray();
                            string content = Encoding.UTF8.GetString(data);
                            JsonSerializerSettings set  = new JsonSerializerSettings();
                            set.TypeNameHandling = TypeNameHandling.Auto;
                            T? deserializeObj = JsonConvert.DeserializeObject<T>(content, set);
                            return deserializeObj;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 从资源文件中抽取资源文件
        /// </summary>
        /// <param name="resFileName">资源文件名称（资源文件名称必须包含目录，目录间用“.”隔开,最外层是项目默认命名空间）</param>
        /// <param name="outputFile">输出文件</param>
        public static void ExtractResFile(string resFileName, string outputFile) {
            BufferedStream inStream = null;
            FileStream outStream = null;
            try {
                Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源
                inStream = new BufferedStream(asm.GetManifestResourceStream(resFileName));
                outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);

                byte[] buffer = new byte[1024];
                int length;

                while((length = inStream.Read(buffer, 0, buffer.Length)) > 0) {
                    outStream.Write(buffer, 0, length);
                }
                outStream.Flush();
            } finally {
                if(outStream != null) {
                    outStream.Close();
                }
                if(inStream != null) {
                    inStream.Close();
                }
            }
        }
    }
}
